﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AntiObesity.Base.Managers;
using AntiObesity.DatabaseAccess;
using System.IO;
using AntiObesity.Base;

namespace AntiObesity.Services.Database
{
    /// <summary>
    /// Clears all data from DB and fill it with basic data
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class InitDB : System.Web.Services.WebService
    {

        [WebMethod]
        public string InitilizeDatabase(string password)
        {
            try
            {
                if (password != "<fill_password_later>")
                    return "INVALID PASSWORD";

                //IntakeManager.DeleteAll();
                FoodManager.DeleteAll();
                SubcategoryManager.DeleteAll();
                CategoryManager.DeleteAll();
                //UserHistoryManager.DeleteAll();
                //UserManager.DeleteAll();
                //AdministratorManager.DeleteAll();

                Category category = null;
                using (var rd = File.OpenText(Server.MapPath("~/App_Data/categories.txt")))
                {
                    while (!rd.EndOfStream)
                    {
                        var line = rd.ReadLine();
                        var parts = line.Split('\t');
                        parts[0] = Cleanup(parts[0]);
                        parts[1] = Cleanup(parts[1]);
                        if (!String.IsNullOrEmpty(parts[0]))
                        {
                            category = new Category
                            {
                                Name = parts[0]
                            };
                            CategoryManager.Persist(category);
                        }
                        var subcategory = new Subcategory
                        {
                            Name = parts[1],
                            CategoryID = category.ID
                        };
                        try
                        {
                            SubcategoryManager.Persist(subcategory);
                        }
                        catch (Exception err)
                        {
                            throw new Exception(line, err);
                        }
                    }
                }

                var unknown = SubcategoryManager.FindByName("Unknown").First();
                // TODO: foods in xls has no category, when added, change this code
                int foodsWithouCalories = 0;
                int foodsWithInvalidCaloriesValue = 0;
                int insertedFoods = 0;
                using (var rd = File.OpenText(Server.MapPath("~/App_Data/foods.txt")))
                {
                    while (!rd.EndOfStream)
                    {
                        var line = rd.ReadLine();
                        var parts = line.Split('\t');
                        if (parts.Length != 2)
                            continue;
                        parts[0] = Cleanup(parts[0]);
                        parts[1] = Cleanup(parts[1]);
                        if (String.IsNullOrEmpty(parts[1]))
                        {
                            // do not accept foods without calories
                            foodsWithouCalories++;
                            continue;
                        }
                        double calories = 0.0;
                        if (!Double.TryParse(parts[1], out calories))
                        {
                            foodsWithInvalidCaloriesValue++;
                            continue;
                        }
                        var food = new Food
                        {
                            Name = parts[0],
                            Calories = (float)calories,
                            SubcategoryID = unknown.ID
                        };
                        try
                        {
                            FoodManager.Persist(food);
                            insertedFoods++;
                        }
                        catch (Exception err)
                        {
                            throw new Exception(line, err);
                        }
                    }
                }
                return String.Format(
                    "DONE. {0} foods inserted, {1} foods found without calories information, {2} foods with invalid calories value",
                    insertedFoods,
                    foodsWithouCalories,
                    foodsWithInvalidCaloriesValue);
            }
            catch (Exception err)
            {
                return err.ToString();
            }
        }

        /// <summary>
        /// Clean up inserted quote by CSV creator
        /// </summary>
        private string Cleanup(string field)
        {
            if (field.StartsWith("\"") && field.EndsWith("\""))
            {
                // Convert two double quotes "" to one "
                // and remove all other quotes
                return field.Replace("\"\"", "¬").Replace("\"", "").Replace("¬", "\"");
            }
            return field;
        }
    }
}
